package com.xu.controller;

import com.xu.domain.User;
import com.xu.repository.UserRepository;
import com.xu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xu
 * @Date: 2021/3/22 14:27
 * @Version 1.0
 */
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserRepository userRepository;
//    @GetMapping("/")
//    public String index(){
//        return "login";
//    }
    @PostMapping("/register")
    @ResponseBody
    public ModelAndView register(User user){
       user.setId(System.currentTimeMillis());
        userService.register(user);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("msg",user.getName()+"添加成功");
        modelAndView.setViewName("success");
        return modelAndView;
    }

    @GetMapping(value = "/user")
    public String getUsers(@RequestParam(name = "page", defaultValue = "0") int page,
                           @RequestParam(name = "size", defaultValue = "2") int size,
                           Model model){
//        List<User> users=userService.findUsers();
        PageRequest pageRequest=PageRequest.of(page,size);
        Page<User> users=userRepository.findAll(pageRequest);
        List<User> list=new ArrayList<>();
        for (User user:users){
            list.add(user);
        }
        System.out.println("users");
        model.addAttribute("users",users);
        return "users";
    }
}
